package com.cf.game.stage.npc;

import com.cf.Event;
import com.cf.compent.RandomMachine;
import com.cf.core.event.HeartbeatEvent;
import com.cf.core.spirit.Spiriter;
import com.cf.core.stage.Stage;
import com.cf.game.constant.SysConstant;
import com.cf.game.stage.event.MaybePunishEvent;
import com.cf.game.stage.event.PunishEvent;
import com.cf.timer.ExpirationTask;
import com.cf.timer.StageTimingWheel;
import lombok.extern.slf4j.Slf4j;

/**
 * game-server-President
 * 校长
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/5/7 下午 05:58
 */
@Slf4j
public class President extends Spiriter {

    private int mayTimes = 0;

    private boolean needPunishTicket = true;

    /**
     * 试探性张望
     */
    private RandomMachine presidentMaybe = new RandomMachine(SysConstant.maybePunishPercent, 100, "校长张望");

    /**
     * 惩罚task
     */
    private ExpirationTask punishTask = new ExpirationTask(1, getStage().getStageNum() + "-punish-task") {
        @Override
        public String getTaskDispatchId() {
            return getStage().getStageNum();
        }

        @Override
        public void run() {
            getStage().broadcastEvent(new PunishEvent());
        }
    };


    public President(Stage stage) {
        super(stage);
    }

    @Override
    public void clean() {

    }

    @Override
    public void handle(Event event) {
        if (event instanceof HeartbeatEvent) {
            //处理出发惩罚逻辑
            randomPunish();
        }

        if (event instanceof PunishEvent) {
            log.info("收到punishEvent，重置状态为true");
            this.needPunishTicket = true;
        }
    }

    private void randomPunish() {
        boolean maybe = presidentMaybe.next();
        if (maybe && needPunishTicket) {
            log.info("发起一次可能惩罚的信息");
            this.getStage().broadcastEvent(new MaybePunishEvent());
            mayTimes++;
        }
        if (mayTimes >= SysConstant.mayTotrue && needPunishTicket) {
            mayTimes = 0;
            needPunishTicket = false;
            log.info("满足惩罚条件，发起惩罚");
            StageTimingWheel.addTask(punishTask, punishTask.getBeatStepSecond());
        }
    }

    @Override
    public Integer getId() {
        return 0;
    }
}
